package com.mdd.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.admin.LikeAdminThreadLocal;
import com.mdd.admin.service.INewContractService;
import com.mdd.admin.validate.NewContractCreateValidate;
import com.mdd.admin.validate.NewContractSearchValidate;
import com.mdd.admin.validate.NewContractUpdateValidate;
import com.mdd.admin.validate.commons.PageValidate;
import com.mdd.admin.vo.NewContractDetailVo;
import com.mdd.admin.vo.NewContractListedVo;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.NewContract;
import com.mdd.common.mapper.NewContractMapper;
import com.mdd.common.util.TimeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

/**
 * 新建合同基本信息实现类
 * @author LikeAdmin
 */
@Service
public class NewContractServiceImpl implements INewContractService {
        
    @Resource
    NewContractMapper newContractMapper;

    /**
     * 新建合同基本信息列表
     *
     * @author LikeAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<NewContractListedVo>
     */
    @Override
    public PageResult<NewContractListedVo> list(PageValidate pageValidate, NewContractSearchValidate searchValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();

        QueryWrapper<NewContract> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        queryWrapper.orderByDesc("id");

        newContractMapper.setSearch(queryWrapper, searchValidate, new String[]{
            "like:contractName@contract_name:str",
            "like:customerName@customer_name:str",
            "=:amount:str",
            "=:gatheringAmount@gathering_amount:str",
            "eq:contractStartTime@contract_start_time:str",
            "eq:contractEndTime@contract_end_time:str",
            "=:dateContractSigning@date_contract_signing:str",
            "=:isUncoil@is_uncoil:str",
            "=:correspondingCustomer@corresponding_customer:str",
            "=:correspondingBusiness@corresponding_business:str",
            "lte:contractValidTime@contract_valid_time:str",
            "=:partySigner@party_signer:str",
            "=:partyPhone@party_phone:str",
            "=:contractType@contract_type:str",
            "=:partybFirm@partyB_firm:str",
            "=:partybSigner@partyB_signer:str",
            "=:partybPhone@partyB_phone:str",
            "lte:signedDate@signed_date:str",
            "lte:contractDate@contract_date:str",
            "=:remarks:str",
            "=:contractState@contract_state:str",
            "=:collaborator:str",
        });

        IPage<NewContract> iPage = newContractMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<NewContractListedVo> list = new LinkedList<>();
        for(NewContract item : iPage.getRecords()) {
            NewContractListedVo vo = new NewContractListedVo();
            BeanUtils.copyProperties(item, vo);
            // 时间 非空 判断
            if (!"".equals(item.getCreateTime()) && item.getCreateTime() != null) {
                vo.setCreateTime(TimeUtils.timestampToDate(item.getCreateTime()));
            }
            if (!"".equals(item.getUpdateTime()) && item.getUpdateTime() != null) {
                vo.setUpdateTime(TimeUtils.timestampToDate(item.getUpdateTime()));
            }
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 新建合同基本信息详情
     *
     * @author LikeAdmin
     * @param id 主键参数
     * @return NewContract
     */
    @Override
    public NewContractDetailVo detail(Integer id) {
        NewContract model = newContractMapper.selectOne(
                new QueryWrapper<NewContract>()
                    .eq("id", id)
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        NewContractDetailVo vo = new NewContractDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 新建合同基本信息新增
     *
     * @author LikeAdmin
     * @param createValidate 参数
     */
    @Override
    public void add(NewContractCreateValidate createValidate) {
        NewContract model = new NewContract();
        model.setCreator(createValidate.getCreator());
        model.setContractName(createValidate.getContractName());
        model.setAmount(createValidate.getAmount());
        model.setContractId(createValidate.getContractId());
        model.setCustomerName(createValidate.getCustomerName());
        model.setGatheringDate(createValidate.getGatheringDate());
        model.setCurrentState(createValidate.getCurrentState());
        model.setOfficialFee(createValidate.getOfficialFee());
        model.setAgencyFee(createValidate.getAgencyFee());
        model.setGatheringAmount(createValidate.getGatheringAmount());
        model.setCurrentManager(createValidate.getCurrentManager());
        model.setFinalProcessingTime(createValidate.getFinalProcessingTime());
        model.setContractStartTime(createValidate.getContractStartTime());
        model.setContractEndTime(createValidate.getContractEndTime());
        model.setDateContractSigning(createValidate.getDateContractSigning());
        model.setFieldStaffId(createValidate.getFieldStaffId());
        model.setFollowupMethod(createValidate.getFollowupMethod());
        model.setFollowupTime(createValidate.getFollowupTime());
        model.setFollowupStatus(createValidate.getFollowupStatus());
        model.setFollowupPersonnel(createValidate.getFollowupPersonnel());
        model.setUploadAttachment(createValidate.getUploadAttachment());
        model.setFollowupContent(createValidate.getFollowupContent());
        model.setCollaboratorId(createValidate.getCollaboratorId());
        model.setCorrespondingCustomer(createValidate.getCorrespondingCustomer());
        model.setCorrespondingBusiness(createValidate.getCorrespondingBusiness());
        model.setContractAmount(createValidate.getContractAmount());
        model.setContractTco(createValidate.getContractTco());
        model.setContractValidTime(createValidate.getContractValidTime());
        model.setCaseload(createValidate.getCaseload());
        model.setPartySigner(createValidate.getPartySigner());
        model.setPartyPhone(createValidate.getPartyPhone());
        model.setPartyCellphone(createValidate.getPartyCellphone());
        model.setPartyEmail(createValidate.getPartyEmail());
        model.setContractFax(createValidate.getContractFax());
        model.setFieldStaff(createValidate.getFieldStaff());
        model.setContractType(createValidate.getContractType());
        model.setPaymentMethod(createValidate.getPaymentMethod());
        model.setPartybFirm(createValidate.getPartybFirm());
        model.setPartybSigner(createValidate.getPartybSigner());
        model.setPartybPhone(createValidate.getPartybPhone());
        model.setSignedDate(createValidate.getSignedDate());
        model.setContractDate(createValidate.getContractDate());
        model.setDownPayment(createValidate.getDownPayment());
        model.setRemarks(createValidate.getRemarks());
        model.setContractState(createValidate.getContractState());
        model.setNextTime(createValidate.getNextTime());
        model.setCollaborator(createValidate.getCollaborator());
        model.setDepartment(createValidate.getDepartment());

        // 是否开卷
        if (!"".equals(createValidate.getIsUncoil()) && createValidate.getIsUncoil() != null) {
            model.setIsUncoil(String.valueOf("否".equals(createValidate.getIsUncoil()) ? 2 : 1));
        }

        // 设置 操作人信息 以及 创建时间
        model.setUserId(Long.valueOf(LikeAdminThreadLocal.getAdminId()));
        model.setUserName(LikeAdminThreadLocal.get("username").toString());
        model.setCreateTime(String.valueOf(System.currentTimeMillis() / 1000));
        model.setUpdateTime(String.valueOf(System.currentTimeMillis() / 1000));
        model.setIsDelete(0);

        newContractMapper.insert(model);
    }

    /**
     * 新建合同基本信息编辑
     *
     * @author LikeAdmin
     * @param updateValidate 参数
     */
    @Override
    public void edit(NewContractUpdateValidate updateValidate) {
        NewContract model = newContractMapper.selectOne(
                new QueryWrapper<NewContract>()
                    .eq("id",  updateValidate.getId())
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setId(updateValidate.getId());
        model.setCreator(updateValidate.getCreator());
        model.setContractName(updateValidate.getContractName());
        model.setAmount(updateValidate.getAmount());
        model.setContractId(updateValidate.getContractId());
        model.setCustomerName(updateValidate.getCustomerName());
        model.setGatheringDate(updateValidate.getGatheringDate());
        model.setCurrentState(updateValidate.getCurrentState());
        model.setOfficialFee(updateValidate.getOfficialFee());
        model.setAgencyFee(updateValidate.getAgencyFee());
        model.setGatheringAmount(updateValidate.getGatheringAmount());
        model.setCurrentManager(updateValidate.getCurrentManager());
        model.setFinalProcessingTime(updateValidate.getFinalProcessingTime());
        model.setContractStartTime(updateValidate.getContractStartTime());
        model.setContractEndTime(updateValidate.getContractEndTime());
        model.setDateContractSigning(updateValidate.getDateContractSigning());
        model.setFieldStaffId(updateValidate.getFieldStaffId());
        model.setFollowupMethod(updateValidate.getFollowupMethod());
        model.setFollowupTime(updateValidate.getFollowupTime());
        model.setFollowupStatus(updateValidate.getFollowupStatus());
        model.setFollowupPersonnel(updateValidate.getFollowupPersonnel());
        model.setUploadAttachment(updateValidate.getUploadAttachment());
        model.setFollowupContent(updateValidate.getFollowupContent());
        model.setCollaboratorId(updateValidate.getCollaboratorId());
        model.setCorrespondingCustomer(updateValidate.getCorrespondingCustomer());
        model.setCorrespondingBusiness(updateValidate.getCorrespondingBusiness());
        model.setContractAmount(updateValidate.getContractAmount());
        model.setContractTco(updateValidate.getContractTco());
        model.setContractValidTime(updateValidate.getContractValidTime());
        model.setCaseload(updateValidate.getCaseload());
        model.setPartySigner(updateValidate.getPartySigner());
        model.setPartyPhone(updateValidate.getPartyPhone());
        model.setPartyCellphone(updateValidate.getPartyCellphone());
        model.setPartyEmail(updateValidate.getPartyEmail());
        model.setContractFax(updateValidate.getContractFax());
        model.setFieldStaff(updateValidate.getFieldStaff());
        model.setContractType(updateValidate.getContractType());
        model.setPaymentMethod(updateValidate.getPaymentMethod());
        model.setPartybFirm(updateValidate.getPartybFirm());
        model.setPartybSigner(updateValidate.getPartybSigner());
        model.setPartybPhone(updateValidate.getPartybPhone());
        model.setSignedDate(updateValidate.getSignedDate());
        model.setContractDate(updateValidate.getContractDate());
        model.setDownPayment(updateValidate.getDownPayment());
        model.setRemarks(updateValidate.getRemarks());
        model.setContractState(updateValidate.getContractState());
        model.setNextTime(updateValidate.getNextTime());
        model.setCollaborator(updateValidate.getCollaborator());
        model.setDepartment(updateValidate.getDepartment());

        // 设置 操作人信息 以及 更新时间
        model.setUpdateUserId(Long.valueOf(LikeAdminThreadLocal.getAdminId()));
        model.setUpdateUserName(LikeAdminThreadLocal.get("username").toString());
        model.setUpdateTime(String.valueOf(System.currentTimeMillis() / 1000));

        newContractMapper.updateById(model);
    }

    /**
     * 新建合同基本信息删除
     *
     * @author LikeAdmin
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        NewContract model = newContractMapper.selectOne(
                new QueryWrapper<NewContract>()
                    .eq("id", id)
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setIsDelete(1);
        model.setDeleteTime(System.currentTimeMillis() / 1000);
        newContractMapper.updateById(model);
    }

}
